<!-- 这一页是adminpage（后端页面）需要普通用户登录后，在此处完成自己的信息填写。admin用户不能填写。 -->
<template>
  <div>
    <el-row>
      <el-col :span="18">
        <p>欢迎{{ student_id }}请在这里完善自己的信息！</p>
      </el-col>
      <el-col :span="3" :offset="2">
        <!-- 修改密码按钮 -->
        <el-button type="danger" @click="dialogVisible = true">
          修改密码
        </el-button>
      </el-col>
    </el-row>

    <!-- 弹出框 -->
    <el-dialog v-model="dialogVisible" width="40%" align-center>
      <h2 style="text-align: center">修改密码</h2>

      <div>
        <el-col :span="18" :offset="3">
          <el-form
            :model="form_password"
            :rules="rules"
            ref="formRef"
            label-width="80px"
          >
            <el-form-item label="学号" prop="student_id">
              <el-input
                v-model="form_password.student_id"
                placeholder="请输入学号"
              />
            </el-form-item>

            <el-form-item label="原密码" prop="old_password">
              <el-input
                v-model="form_password.old_password"
                placeholder="请输入原密码"
                show-password
              />
            </el-form-item>

            <el-form-item label="新密码" prop="new_password">
              <el-input
                v-model="form_password.new_password"
                placeholder="请输入新密码"
                show-password
              />
            </el-form-item>
          </el-form>
        </el-col>
      </div>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确认修改</el-button>
      </template>
    </el-dialog>
  </div>
  <div>
    <el-col :span="18" :offset="3">
      <el-card style="padding: 30px 20px">
        <!-- 头像 -->

        <el-row justify="center">
          <el-upload
            class="avatar-uploader"
            :action="`${$baseURL}profile/${student_id}/avatar`"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="form.avatar_url"
              :src="`${$baseURL}${form.avatar_url}`"
              class="avatar"
              alt="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-row>
        <div style="text-align: center; margin: 20px">
          第一次登录，请上传头像
        </div>

        <el-form :model="form" label-width="left">
          <!-- 第一行 -->
          <el-row>
            <el-col :span="6">
              <el-form-item label="姓名">
                <el-input placeholder="刘雨乐" v-model="form.full_name" />
              </el-form-item>
            </el-col>
            <el-col :span="7" :offset="1">
              <el-form-item label="出生年月">
                <el-input placeholder="20020610" v-model="form.birth_date" />
              </el-form-item>
            </el-col>
            <el-col :span="9" :offset="1">
              <el-form-item label="家庭住址">
                <el-input placeholder="陕西省-渭南市" v-model="form.address" />
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 第二行 -->
          <el-row>
            <el-col :span="8">
              <el-form-item label="联系电话">
                <el-input placeholder="15191304929" v-model="form.phone" />
              </el-form-item>
            </el-col>
            <el-col :span="8" :offset="1">
              <el-form-item label="邮箱">
                <el-input
                  placeholder="1022835493@qq.com"
                  v-model="form.email"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6" :offset="1">
              <el-form-item label="工作类别">
                <el-select v-model="form.job_type" placeholder="请选择">
                  <el-option
                    v-for="item in job_types"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 第三行 -->

          <el-row>
            <el-col :span="5">
              <el-form-item label="导师">
                <el-input placeholder="张延滋" v-model="form.advisor" />
              </el-form-item>
            </el-col>
            <el-col :span="5" :offset="1">
              <el-form-item label="学历">
                <el-input placeholder="硕士" v-model="form.degree" />
              </el-form-item>
            </el-col>
            <el-col :span="5" :offset="1">
              <el-form-item label="状态">
                <el-select v-model="form.acad_status" placeholder="请选择">
                  <el-option
                    v-for="item in academic_status"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5" :offset="1">
              <el-form-item label="毕业时间">
                <el-input
                  placeholder="20270610"
                  v-model="form.graduation_date"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- row-6 -->
          <el-row>
            <el-col :span="8">
              <el-form-item label="所在省份">
                <el-select
                  v-model="form.workplace"
                  placeholder="请选择省份或直辖市"
                >
                  <el-option
                    v-for="item in provinces"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6" :offset="1">
              <el-form-item label="工作单位">
                <el-input
                  placeholder="北京理工大学"
                  v-model="form.organization"
                />
              </el-form-item>
            </el-col>

            <el-col :span="8" :offset="1">
              <el-form-item label="岗位">
                <el-input placeholder="算法工程师" v-model="form.job_title" />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 第四行 -->

          <el-row>
            <el-col :span="24">
              <el-form-item label="研究方向">
                <el-input
                  :autosize="{ minRows: 2, maxRows: 10 }"
                  type="textarea"
                  placeholder="请描述自己的研究方向"
                  v-model="form.research_direction"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <!-- row-5 -->
          <el-row>
            <el-col>
              <el-form-item label="个人简介">
                <el-input
                  :autosize="{ minRows: 2, maxRows: 10 }"
                  type="textarea"
                  placeholder="请在此处填写你的个人简介"
                  v-model="form.introduction"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <!-- row -->
          <el-row>
            <el-col>
              <el-form-item label="个人成果">
                <el-input
                  :autosize="{ minRows: 2, maxRows: 10 }"
                  type="textarea"
                  placeholder="请在此处填写你的个人成果"
                  v-model="form.achievements"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 给自己添加的标签 -->
          <el-row>
            <el-col>
              <el-form-item label="个人标签">
                <el-input
                  placeholder="请在此处填写个人标签，（不超过4个），用-分割，如天然呆-选择恐惧-仙气十足"
                  v-model="form.tag"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <el-row justify="center">
          <el-button type="success" @click="saveProfile">保存</el-button>
        </el-row>
      </el-card>
    </el-col>
  </div>

  <div></div>
</template>

<script setup>
import { reactive, onMounted } from "vue";
import { ref } from "vue";
import { Plus } from "@element-plus/icons-vue";
import api from "@/utils/api";
import { ElMessage } from "element-plus";

//修改密码
const dialogVisible = ref(false);
const formRef = ref(null);

const form_password = ref({
  student_id: "",
  old_password: "",
  new_password: "",
});

// 校验规则
const rules = {
  student_id: [{ required: true, message: "请输入学号", trigger: "blur" }],
  old_password: [{ required: true, message: "请输入原密码", trigger: "blur" }],
  new_password: [{ required: true, message: "请输入新密码", trigger: "blur" }],
};

// 提交修改请求
const handleSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) return;

    try {
      const res = await api.post("/change_password", form_password.value, {
        headers: { auth: true },
      });

      if (res.data.code === 200) {
        ElMessage.success("密码修改成功");
        dialogVisible.value = false;
        localStorage.removeItem("token");
        window.location.href = "/login";
      } else {
        ElMessage.error(res.data.msg || "修改失败");
      }
    } catch (err) {
      ElMessage.error("请求失败，请稍后再试");
      console.error(err);
    }
  });
};

// 学号（从登录后拿）
// 从 localStorage/sessionStorage 获取学号
const student_id = ref(
  localStorage.getItem("student_id") ||
    sessionStorage.getItem("student_id") ||
    ""
);

const academic_status = [
  { value: "在校生", label: "在校生" },
  { value: "已毕业", label: "已毕业" },
];

const job_types = [
  { value: "国企", label: "国企" },
  { value: "互联网", label: "互联网" },
  { value: "政府", label: "政府" },
  { value: "高校", label: "高校" },
  { value: "深造", label: "深造" },
];

const provinces = [
  { value: "北京市", label: "北京市" },
  { value: "天津市", label: "天津市" },
  { value: "上海市", label: "上海市" },
  { value: "重庆市", label: "重庆市" },
  { value: "河北省", label: "河北省" },
  { value: "山西省", label: "山西省" },
  { value: "辽宁省", label: "辽宁省" },
  { value: "吉林省", label: "吉林省" },
  { value: "黑龙江省", label: "黑龙江省" },
  { value: "江苏省", label: "江苏省" },
  { value: "浙江省", label: "浙江省" },
  { value: "安徽省", label: "安徽省" },
  { value: "福建省", label: "福建省" },
  { value: "江西省", label: "江西省" },
  { value: "山东省", label: "山东省" },
  { value: "河南省", label: "河南省" },
  { value: "湖北省", label: "湖北省" },
  { value: "湖南省", label: "湖南省" },
  { value: "广东省", label: "广东省" },
  { value: "海南省", label: "海南省" },
  { value: "四川省", label: "四川省" },
  { value: "贵州省", label: "贵州省" },
  { value: "云南省", label: "云南省" },
  { value: "陕西省", label: "陕西省" },
  { value: "甘肃省", label: "甘肃省" },
  { value: "青海省", label: "青海省" },
  { value: "台湾省", label: "台湾省" },
  { value: "内蒙古自治区", label: "内蒙古自治区" },
  { value: "广西壮族自治区", label: "广西壮族自治区" },
  { value: "西藏自治区", label: "西藏自治区" },
  { value: "宁夏回族自治区", label: "宁夏回族自治区" },
  { value: "新疆维吾尔自治区", label: "新疆维吾尔自治区" },
  { value: "香港特别行政区", label: "香港特别行政区" },
  { value: "澳门特别行政区", label: "澳门特别行政区" },
];

// 表单数据
const form = reactive({
  full_name: "",
  birth_date: "",
  address: "",
  phone: "",
  email: "",
  advisor: "",
  degree: "",
  graduation_date: "",
  workplace: "",
  organization: "",
  job_type: "",
  job_title: "",
  research_direction: "",
  acad_status: "",
  introduction: "",
  achievements: "",
  tag: "",
  avatar_url: "",
});

// 获取已有数据
const fetchProfile = async () => {
  try {
    const res = await api.get(`/profile/${student_id.value}`);
    if (res.data.code === 200) {
      Object.assign(form, res.data.data); // 更新表单
    }
  } catch (err) {
    console.log("第一次登录，暂无资料");
  }
};

// 保存数据
const saveProfile = async () => {
  try {
    const res = await api.post(`/profile/${student_id.value}`, form);
    if (res.data.code === 200) {
      alert("保存成功！");
    }
  } catch (err) {
    alert("保存失败！");
    console.error(err.response?.data || err.message);
  }
};

// 处理头像上传
const handleAvatarSuccess = (res) => {
  form.avatar_url = res.avatar_url + "?t=" + Date.now();
  console.log("新头像：", form.avatar_url);
};

const beforeAvatarUpload = (file) => {
  const isImage = ["image/jpeg", "image/png", "image/gif"].includes(file.type);
  const isLt2M = file.size / 1024 / 1024 < 10;
  if (!isImage) {
    alert("上传头像只能是 JPG/PNG/GIF 格式!");
  }
  if (!isLt2M) {
    alert("上传头像大小不能超过 10MB!");
  }
  return isImage && isLt2M;
};

onMounted(() => {
  fetchProfile();
});
</script>

<style scoped>
.el-row {
  padding: 5px 0;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover; /* ✅ 保持原比例完整显示 */
  background-color: #f6f6f6; /* 背景淡灰防止透明图片突兀 */
  border: 1px solid #e5e5e5;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
